import 'package:dio/dio.dart';
import 'package:duo_zui/Util/config_color.dart';
import 'package:duo_zui/model/model.dart';
import 'package:duo_zui/widget/AppWidget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'articelDetailPage/webViewPage.dart';

class SliverContainer extends StatefulWidget {
  final String url;

  SliverContainer({Key key, @required this.url}) : super(key: key);

  @override
  _SliverContainerState createState() => _SliverContainerState();
}

class _SliverContainerState extends State<SliverContainer> with AutomaticKeepAliveClientMixin{

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    url = widget.url;
    _onRefresh();
  }

  _onScrollNotification(ScrollNotification scrollInfo) {
    if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) {
      //滑到了底部
      _fetchPostMoreData();
    }
  }

  List<App> items = List<App>();
  dynamic lastKey = 0;
  String url;
  bool isbottem = false;

  Future<List<App>> fetchPost() async {
    lastKey = 0;
    Dio dio = new Dio();
    var list = List<App>();
    print('$url$lastKey');
    Response response = await dio.get("$url$lastKey");
    Reslut reslut = Reslut.fromJson(response.data);
    if(!reslut.response.hasMore){
      return list;//如果没有数据就不继续了
    }
    lastKey = reslut.response.lastKey;//更新lastkey
    list.addAll(reslut.response.apps);
    return list;
  }

  void _fetchPostMoreData() async {
    Dio dio = new Dio();
    var list = List<App>();
    print('$url$lastKey');
    Response response = await dio.get("$url$lastKey");
    Reslut reslut = Reslut.fromJson(response.data);
    if(!reslut.response.hasMore){
      setState(() {
        isbottem = true;
      });
      return;//如果没有数据就不继续了
    }
    lastKey = reslut.response.lastKey;//更新lastkey
    list.addAll(reslut.response.apps);
    setState(() {
      items.addAll(list);
    });
  }

  Future<Null> _onRefresh() async {
    await fetchPost().then((list) {
      setState(() {
        items.clear();
        items.addAll(list);
        Fluttertoast.showToast(msg: "已刷新");
        return null;
      });
    });
  }

  Future<Null> _getMoreData() async {
    await fetchPost().then((list) {
      setState(() {
        print(list);
        items.addAll(list);
        return null;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return getContentSliver(context, items);
  }

  getContentSliver(BuildContext context, List<App> list) {

    print('getContentSliver');
    if (list == null || list.length == 0) {
      return Text('暂无数据');
    }
    return SafeArea(
      top: false,
      bottom: false,
      child: Builder(
        // This Builder is needed to provide a BuildContext that is "inside"
        // the NestedScrollView, so that sliverOverlapAbsorberHandleFor() can
        // find the NestedScrollView.
        builder: (BuildContext context) {
          return NotificationListener<ScrollNotification>(
              child: RefreshIndicator(
                    notificationPredicate: (notifation) {
                      return true;
                    },
                    onRefresh:(()=>_onRefresh()),
                    color: Colors.green,
                    child:CustomScrollView(
                      physics: const BouncingScrollPhysics(),
                      // The "controller" and "primary" members should be left
                      // unset, so that the NestedScrollView can control this
                      // inner scroll view.
                      // If the "controller" property is set, then this scroll
                      // view will not be associated with the NestedScrollView.
                      // The PageStorageKey should be unique to this ScrollView;
                      // it allows the list to remember its scroll position when
                      // the tab view is not on the screen.
                      key: PageStorageKey<String>("我的"),
                      //controller: _scrollController,
                      slivers: <Widget>[
                        SliverOverlapInjector(
                          // This is the flip side of the SliverOverlapAbsorber above.
                          handle:
                          NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                        ),
                        SliverList(
                            delegate: SliverChildBuilderDelegate(
                                ((BuildContext context, int index) {
                                  if(index < items.length){
                                     return getItemView(items, index);
                                  }else{
                                    if(isbottem){
                                      return Align(
                                        alignment: Alignment.center,
                                        child: Text('已经到底了',style: TextStyle(fontSize: 13.0, color: ConfigColor.colorText2,decoration: TextDecoration.none)),
                                      );
                                    }else{
                                      return _buildProgressIndicator();
                                    }
                                  }
                                }), childCount: items.length+1)),
                      ],
                    )),
            onNotification: (ScrollNotification scrollInfo) => _onScrollNotification(scrollInfo),
          );
        },
      ),
    );
  }

  double singleLineImgHeight = 180.0;
  double contentVideoHeight = 350.0;

  Widget getItemView(List<App> apps, int index) {
    Widget widget = AppWidget(context, apps[index]);
    return GestureDetector(
      onTap: (){
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => WebViewPage(url: 'http://www.appshuo.club/appview/app-desc/${apps[index].id}',title: 'APP详情页',)));
      },
      child: widget,
    );
  }
}

///上拉加载更多
Widget _buildProgressIndicator() {
  ///是否需要显示上拉加载更多的loading
  Widget bottomWidget = new Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
    ///loading框
    new SpinKitThreeBounce(color: Color(0xFF24292E)),
    new Container(
      width: 5.0,
    ),
  ]);
  return new Padding(
    padding: const EdgeInsets.all(10.0),
    child: new Center(
      child: bottomWidget,
    ),
  );
}